import React, { useContext } from "react";
import { SwitchLoading, SwitchUnchecedkLoading } from "@ct0/icons";
import classNames from "classnames";
import { ThemeContext } from "../theme";
import { useStyles } from "./styles";

import type { SwitchProps } from "./type";

function Switch({
  loading,
  disabled,
  openText,
  closeText,
  value = false,
  onChange,
}: SwitchProps) {
  const { fontSize } = useContext(ThemeContext);
  const classes = useStyles({ fontSize });
  const isOpen = value;

  if (loading) disabled = true;

  const onClick = () => !disabled && onChange?.(!value);

  return (
    <div
      role="switch"
      className={classNames(
        classes.switch,
        disabled && classes.disabled,
        isOpen && classes.open
      )}
      onClick={onClick}
    >
      <div
        className={classNames(
          classes.handler,
          isOpen ? classes.right : classes.left,
          disabled && classes.notAllowed
        )}
      >
        {loading && (
          <div className={classes.loading}>
            {isOpen ? <SwitchLoading /> : <SwitchUnchecedkLoading />}
          </div>
        )}
      </div>
      <span>{isOpen ? openText : closeText}</span>
    </div>
  );
}

export default Switch;
